(function(){
	let Game = window.Game = function(params){
		this.canvas = document.getElementById(params.id);
		this.ctx = this.canvas.getContext("2d");
		this.jsonUrl = params.jsonUrl;
		//帧编号
		this.fno = 0;
		this.init();
		//鼠标控制起飞
		this.isJump = false;
		this.loadResources(() => {
			this.start();
		})
	}
	
	//初始化宽高
	Game.prototype.init = function(){
		let windowW = document.documentElement.clientWidth;
		let windowH = document.documentElement.clientHeight;
		if(windowW > 450) windowW = 450
		if(windowW < 350) windowW = 350
		if(windowH > 820) windowH = 820
		if(windowH < 500) windowH = 500
		this.canvas.width = windowW;
		this.canvas.height = windowH;
	}
	
	//预加载所有资源
	Game.prototype.loadResources = function(cb){
		let xhr = new XMLHttpRequest();
		this.R = {};
		xhr.open('get',this.jsonUrl,true);
		xhr.onreadystatechange = () => {
			if(xhr.readyState == 4 || xhr.readyState == 200){
				let jsonObj = JSON.parse(xhr.responseText);
				jsonObj.imgs.forEach((item,index) => {
					this.R[item.name] = new Image();
					this.R[item.name].src = item.url;
					this.R[item.name].onload = () => {
						this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
						this.ctx.font="20px Georgia";
						let txt = '资源正在加载中 ' + (index + 1) + '/' + jsonObj.imgs.length + '，请稍后...';
						this.ctx.textAlign = 'center';
						this.ctx.fillText(txt,this.canvas.width / 2,this.canvas.height * (1 - 0.618));
						if(jsonObj.imgs.length == (index + 1)){
							cb();
						} 
					}
				})
			}
		}
		xhr.send(null);
	}
	
	//游戏开始
	Game.prototype.start = function(){
		this.bg = new Background();
		this.land = new Land();
		this.pipeArr = [];
		this.bird = new Bird();
		this.timer = setInterval(() => {
			//清屏
			this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
			
			//背景移动
			this.bg.init();
			this.bg.move();
			this.land.init();
			this.land.move();
			
			//管子移动
			this.pipeArr.forEach(item => {
				item.init();
				item.move();
			})
			
			//小鸟出击
			// this.bird.init();
			this.bird.fly(); 
			
			//每150帧出一对管子
			if(this.fno % 150 == 0) new Pipe();
			
			//帧编号
			this.fno++;
			this.ctx.font = "16px consolas";
			this.ctx.textAlign = 'left';
			this.ctx.fillText('FNO: ' + this.fno,10,20);
		},20)
	}
	
})();